package examples.distributedsession;

import examples.distributedsession.support.CookieHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

/**
 * @author Bill
 * @version 2013-05-28
 */
public class DSHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private static Logger logger = LoggerFactory.getLogger(DSHttpServletRequestWrapper.class);

    private HttpServletRequest wrapper;

    private SessionManager sessionManager;
    private HttpSession session;

    /**
     * Constructs a request object wrapping the given request.
     *
     * @throws IllegalArgumentException if the request is null
     */
    public DSHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        wrapper = request;
    }

    @Override
    public HttpSession getSession(boolean create) {
        //检查Session管理器
        if (sessionManager == null && create) {
            throw new IllegalStateException("No SessionHandler or SessionManager");
        }
        if (session != null && sessionManager != null) {
            return session;
        }

        session = null;

        //从客户端cookie中查找Session ID
        String id = sessionManager.getRequestSessionId(wrapper);
        logger.debug("获取客户端的Session ID:[" + id + "]");
        if (id != null && sessionManager != null) {
            //如果存在，则先从管理器中取
            session = sessionManager.getHttpSession(id, wrapper);
            if (session == null && !create) {
                return null;
            }
        }
        //否则实例化一个新的Session对象
        if (session == null && sessionManager != null && create) {
            session = sessionManager.newHttpSession(wrapper);
        }
        return session;
    }

    private class SessionManager {

        String getRequestSessionId(HttpServletRequest request) {
            return CookieHelper.findSessionId(request);
        }

        HttpSession newHttpSession(HttpServletRequest request) {
            return null;
        }

        HttpSession getHttpSession(String sessionId, HttpServletRequest request) {
            return null;
        }
    }
}
